//
//  DLWeChatPayOrAuthToolsShareManager.m
//  DGGSharePaySDK
//
//  Created by Dracy on 2019/8/20.
//  Copyright © 2019 dl_hzk. All rights reserved.
//

#import "DLWeChatPayOrAuthToolsManager.h"
#import "WXApi.h"
#import <CommonCrypto/CommonDigest.h>
#import <UShareUI/UShareUI.h>
#import "DLWeChatShareMsgModel.h"
#import "DLWeChatPayOrAuthConfig.h"
/**
 *
 *  此处必须保证在Info.plist 中的 URL Types 的 Identifier 对应一致
 */
#define WeiXinTypeUrl @"weixin"


DLWeChatPayToolsParameterKey const DLWeChatPayToolsParameterAPPIDKey = @"appid";
DLWeChatPayToolsParameterKey const DLWeChatPayToolsParameterRetcodeKey = @"retcode";
DLWeChatPayToolsParameterKey const DLWeChatPayToolsParameterPrepayIDKey = @"prepay_id";
DLWeChatPayToolsParameterKey const DLWeChatPayToolsParameterNonceStrKey = @"nonce_str";
DLWeChatPayToolsParameterKey const DLWeChatPayToolsParameterPackageKey = @"package";
DLWeChatPayToolsParameterKey const DLWeChatPayToolsParameterPartnerIDKey = @"partnerid";
DLWeChatPayToolsParameterKey const DLWeChatPayToolsParameterTimestampKey = @"timestamp";
DLWeChatPayToolsParameterKey const DLWeChatPayToolsParameterBussinessAPIKey = @"bussiness_api_key";

DLWeChatPayToolsParameterKey const DLWeChatPayToolsParameterOrderRequestStringKey = @"order_request_string";
//DLWeChatPayToolsParameterKey const DLWeChatPayToolsParameterAPPSchemeKey = @"DLappmerchant";

@interface DLWeChatPayOrAuthToolsManager()<WXApiDelegate,UMSocialShareMenuViewDelegate>
@property (nonatomic, strong) DLWeChatShareMsgModel *shareMsgModel;
@property (nonatomic, assign) DLWeChatPayOrAuthCustomPlatformType currentType;
@property (nonatomic, copy) void (^responseBlock)(NSDictionary *, NSError *);
@property (nonatomic,copy) DLWeChatPayManagerBack payBack;

@end

@implementation DLWeChatPayOrAuthToolsManager

+ (instancetype)sharedInstance
{
    static DLWeChatPayOrAuthToolsManager *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[DLWeChatPayOrAuthToolsManager alloc] init];
    });
    return _sharedInstance;
}

#pragma mark - 通用

+ (BOOL)dl_isHandlePayURL:(NSURL *)theURL
{
    if ([theURL.absoluteString rangeOfString:@"://pay"].length != 0)
    {//微信支付
        return YES;
    }
    
    return NO;
}

- (BOOL)dl_handleOpenURL:(NSURL *)theURL{
    return [self dl_handleOpenURL:theURL universalLink:nil];
}

- (BOOL)dl_handleOpenURL:(NSURL *)theURL universalLink:(NSUserActivity *)userActivity
{
    if ([theURL.absoluteString rangeOfString:@"://pay"].length != 0)
    {//微信支付
        return [self dl_WeiXinHandleOpenURL:theURL];
    }else if (theURL.host == nil && theURL.query == nil){
        if(userActivity){
            return [WXApi handleOpenUniversalLink:userActivity delegate:self];
        }else{
            return [WXApi handleOpenURL:theURL delegate:self];
        }
    }
    //微信WeChat分享回调
    if([theURL.host isEqualToString:@"platformId=wechat"] ||
       [theURL.host isEqualToString:@"oauth"] ||
       [theURL.absoluteString rangeOfString:@"wx_auth"].location != NSNotFound ||
       [theURL.absoluteString rangeOfString:@"wechat_auth"].location != NSNotFound){
        if(userActivity){
            return [WXApi handleOpenUniversalLink:userActivity delegate:self];
        }else{
            return [WXApi handleOpenURL:theURL delegate:self];
        }
    }
    return NO;
}

#pragma mark -
#pragma mark - 微信相关

+ (BOOL)dl_WeiXinIsInstalled
{
    return [WXApi isWXAppInstalled];
}

- (BOOL)dl_WeiXinHandleOpenURL:(NSURL *)theUrl
{
    return [WXApi handleOpenURL:theUrl delegate:self];
}

- (void)dl_WeiXinPayWithParameters:(NSDictionary <DLWeChatPayToolsParameterKey, id> *)theParam response:(nonnull void (^)(NSDictionary * _Nullable, NSError * _Nullable))theResponse
{
    self.responseBlock = theResponse;
    
    if (![WXApi isWXAppInstalled])
    {
        UIAlertView *tView = [[UIAlertView alloc]initWithTitle:@"提示"
                                                       message:@"未安装微信客户端，请使用其它支付方式。"
                                                      delegate:nil
                                             cancelButtonTitle:@"确定"
                                             otherButtonTitles:nil];
        [tView show];
        
        if (self.responseBlock)
        {
            self.responseBlock(nil, [NSError errorWithDomain:NSCocoaErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey: @"未安装微信客户端!"}]);
        }
        
        return;
    }
    
    if (theParam)
    {
        NSString *tResultCode = theParam[DLWeChatPayToolsParameterRetcodeKey];
        
        if (tResultCode.integerValue == 0)
        {
            PayReq *tReq = [[PayReq alloc]init];
            
            tReq.partnerId = theParam[DLWeChatPayToolsParameterPartnerIDKey];
            tReq.prepayId = theParam[DLWeChatPayToolsParameterPrepayIDKey];
            tReq.nonceStr = theParam[DLWeChatPayToolsParameterNonceStrKey];
            tReq.package = @"Sign=WXPay";
            
            NSDate *tCurrentDate = [NSDate date];
            tReq.timeStamp = (UInt32)tCurrentDate.timeIntervalSince1970;
            
            tReq.sign = [self signWithAppID:theParam[DLWeChatPayToolsParameterAPPIDKey]
                                  partnerID:tReq.partnerId
                                   prepayID:tReq.prepayId
                                    package:tReq.package
                                   nonceStr:tReq.nonceStr
                                  timestamp:tReq.timeStamp
                            bussinessAPIKey:theParam[DLWeChatPayToolsParameterBussinessAPIKey]];
            
            [WXApi sendReq:tReq completion:^(BOOL success) {
                
            }];
        }
        else
        {
            NSLog(@"win xin pay lose:%@", theParam[@"retmsg"]);
        }
    }
    else
    {
        if (self.responseBlock)
        {
            self.responseBlock(nil, [NSError errorWithDomain:NSCocoaErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey: @"输入参数为空!"}]);
        }
    }
}

//创建发起支付时的sige签名
- (NSString *)signWithAppID:(NSString *)theAppID partnerID:(NSString *)thePartnerID prepayID:(NSString *)thePrepayID package:(NSString *)thePackage nonceStr:(NSString *)theNonceStr timestamp:(UInt32)theTimeStamp bussinessAPIKey:(NSString *)theBusinessAPIKey
{
    NSDictionary *tSignParams = @{DLWeChatPayToolsParameterAPPIDKey: theAppID,
                                  @"noncestr": theNonceStr,
                                  DLWeChatPayToolsParameterPackageKey: thePackage,
                                  DLWeChatPayToolsParameterPartnerIDKey: thePartnerID,
                                  @"prepayid": thePrepayID,
                                  DLWeChatPayToolsParameterTimestampKey: [NSString stringWithFormat:@"%u", (unsigned int)theTimeStamp]};
    
    NSMutableString *tContentStr  = [NSMutableString string];
    
    //按字母顺序排序
    NSArray *tSortedKeys = [[tSignParams allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //拼接字符串
    for (NSString *tKey in tSortedKeys)
    {
        if (![tSignParams[tKey] isEqualToString:@""] &&
            ![tSignParams[tKey] isEqualToString:@"sign"] &&
            ![tSignParams[tKey] isEqualToString:@"key"]
            )
        {
            [tContentStr appendFormat:@"%@=%@&", tKey, tSignParams[tKey]];
        }
    }
    
    [tContentStr appendFormat:@"key=%@", theBusinessAPIKey];
    [tContentStr stringByReplacingOccurrencesOfString:@"_" withString:@""];
    NSString *result = [self MD5:tContentStr];
    
    return result;
}

- (NSString *)MD5:(NSString *)theBaseStr
{
    const char *cStr = [theBaseStr UTF8String];
    unsigned char result[16]= "0123456789abcdef";
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

#pragma mark -

/*
 微信授权
 */
- (void)dl_WeiXinWithAuthParameter:(id)parameter schemeKey:(NSString *)schemeKey callBack:(DLWeChatPayManagerBack)payBack{
    // 判断手机有没有微信
    if ([WXApi isWXAppInstalled]) {
        NSLog(@"安装了微信");
    }else{
        NSLog(@"还没有安装微信");
    }
    NSAssert(parameter, @"订单信息不能为空");
    // 发起支付
    self.payBack = payBack;
    if ([parameter isKindOfClass:[SendAuthReq class]]) {
        //微信
        [WXApi sendReq:(SendAuthReq *)parameter completion:^(BOOL success) {
            
        }];
    }else if ([parameter isKindOfClass:[NSString class]]){
    }
}

/*
微信打开小程序
 */
- (void)dl_WeiXinMiniProgramWithUserName:(NSString *)userName
                                    path:(NSString *)path
                         miniProgramType:(NSUInteger)miniProgramType
                                  extMsg:(NSString *)extMsg
                                 extDict:(NSDictionary *)extDict
                                response:(void (^)(NSDictionary * _Nullable response, NSError * _Nullable err))theResponse{
    self.responseBlock = theResponse;
    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
    launchMiniProgramReq.userName = userName;  //拉起的小程序的username
    launchMiniProgramReq.path = path;
    ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
    launchMiniProgramReq.miniProgramType = miniProgramType; //拉起小程序的类型
    launchMiniProgramReq.extMsg = extMsg;
    launchMiniProgramReq.extDic = extDict;
    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
        NSLog(@"___调起小程序：%@", success ? @"成功":@"失败");
    }];
}

#pragma mark -
#pragma mark - WXApiDelegate
#pragma mark - 处理自定义分享结果回调

- (void)onResp:(BaseReq *)resp {
    if ([resp isKindOfClass:[WXLaunchMiniProgramResp class]]){
        WXLaunchMiniProgramResp *rsp = resp;
         NSString *string = rsp.extMsg;
         // 对应JsApi navigateBackApplication中的extraData字段数据
        if(self.responseBlock){
            self.responseBlock(@{@"errCode": @(rsp.errCode),
                                 @"errStr": rsp.errStr ?: @"",
                                 @"extMsg": rsp.extMsg?:@""}, nil);
        }
    }
    
    if ([resp isKindOfClass:[PayResp class]])
    {
        PayResp *response = (PayResp *)resp;
        
        switch(response.errCode)
        {
            case WXSuccess:
                //服务器端查询支付通知或查询API返回的结果再提示成功
                NSLog(@"支付成功");
                break;
            default:
                NSLog(@"支付失败，retcode=%d",response.errCode);
                break;
        }
        
        if (self.responseBlock)
        {
            self.responseBlock(@{@"errCode": @(response.errCode), @"errStr": response.errStr ?: @""}, nil);
        }
    }
    
    if([resp isKindOfClass:[SendAuthResp class]])
    {//判断是否为授权登录类
        
        SendAuthResp *req = (SendAuthResp *)resp;
        if([req.state isEqualToString:@"wx_auth"]){//微信授权成功
            if(req && req.code){
                if(req.errCode == WXSuccess){
                    if(self.payBack){
                        NSString *errorCode = [NSString stringWithFormat:@"%d",req.errCode];
                        NSString *code = [NSString stringWithFormat:@"%@",req.code];
                        self.payBack(@{@"code":errorCode, @"authCode":code});
                    }
                }else{
                    if(self.payBack){
                        NSString *errorCode = [NSString stringWithFormat:@"%d",req.errCode];
                        NSString *msg = [NSString stringWithFormat:@"%@",req.errStr];
                        self.payBack(@{@"code":errorCode, @"authCode":@"", @"msg": msg});
                    }
                }
            }else{
                self.payBack(@{@"code":@"-1",@"authCode": @"", @"msg":@"未知错误"});
            }
        }else{
            self.payBack(@{@"code":@"-1",@"authCode": @"", @"msg":@"未知错误"});
        }
    }
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {//微信分享成功
        [self handleOpenWechatResp:resp];
    }
}

- (void)onReq:(BaseReq *)req
{
    NSLog(@"%@", req);
}



#pragma mark - /////////////////////////////////////////微信分享///////////////////////////////////
#pragma mark - 分享

- (void)dl_shareToWX:(UMSocialPlatformType)platformType
         withMediaURL:(NSString *)url
             thumbURL:(NSString *)thumbURL
                title:(NSString *)title
              content:(NSString *)content{
    if(!self.delegate){
        UIWindow *rootWindow = [UIApplication sharedApplication].keyWindow;
        if([rootWindow.rootViewController valueForKey:@"mainViewController"] && [[rootWindow.rootViewController valueForKey:@"mainViewController"] isKindOfClass:([UITabBarController class])]){
            self.delegate = (id <WXSharedMesaageDelegate>)[(UINavigationController *)[(UITabBarController *)[rootWindow.rootViewController valueForKey:@"mainViewController"] selectedViewController] topViewController];
        }else{
            if([rootWindow.rootViewController isKindOfClass:([UINavigationController class])]){
                self.delegate = (id <WXSharedMesaageDelegate>)((UINavigationController *)rootWindow.rootViewController).topViewController;
            }else{
                self.delegate = (id <WXSharedMesaageDelegate>)rootWindow.rootViewController;
            }
        }
    }
    
    //存储分享信息
    self.shareMsgModel = nil;
    DLWeChatShareMsgModel *msgModel = [[DLWeChatShareMsgModel alloc] init];
    msgModel.title = title;
    msgModel.content = content;
    msgModel.mediaURL = url;
    msgModel.thumbURL = thumbURL;
    self.shareMsgModel = msgModel;
    [UMSocialUIManager setShareMenuViewDelegate:self];
    __weak typeof(self) weakSelf = self;
    //添加默认分享平台
#if 0
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine)]];
#else
    [self dl_shareAddCustomePlatform:DLWeChatPayOrAuthCustomPlatformTypeWechatSession iconImage:[UIImage imageNamed:@"umsocial_wechat"] platformName:@"微信"];
    [self dl_shareAddCustomePlatform:DLWeChatPayOrAuthCustomPlatformTypeWechatTimeLine iconImage:[UIImage imageNamed:@"umsocial_wechat_timeline"] platformName:@"微信朋友圈"];
#endif
    if([self.delegate respondsToSelector:@selector(dl_shareCustomeConfigCheck:)]){
        [self.delegate dl_shareCustomeConfigCheck:self];
    }
    
    if (self.customWxShareUI) {
        [self handleShareActionWithPlatformType:self.WXSharePlatformType userInfo:nil];
        return;
    }
    
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        if(platformType == UMSocialPlatformType_WechatSession || platformType == UMSocialPlatformType_WechatTimeLine){
            // 根据获取的platformType确定所选平台进行下一步操作
            //创建分享消息对象
            UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
            //创建网页内容对象
            UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:content thumImage:thumbURL];
            //设置网页地址
            shareObject.webpageUrl = url;
            //分享消息对象设置分享内容对象
            messageObject.shareObject = shareObject;
            //调用分享接口
            [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:weakSelf.delegate completion:^(id data, NSError *error) {
                [weakSelf handleMessageBack:data error:error];
            }];
        }else{
            self.currentType = platformType;
            //自定义分享平台
            [weakSelf handleShareActionWithPlatformType:platformType userInfo:userInfo];
        }
    }];
}

- (void)dl_shareWithMediaURL:(NSString *)url
                     thumbURL:(NSString *)thumbURL
                        title:(NSString *)title
                      content:(NSString *)content{
    [self dl_shareToWX:UMSocialPlatformType_WechatSession withMediaURL:url thumbURL:thumbURL title:title content:content];
}

- (void)dgg_shareImageToWXPlatformWithSence:(enum WXScene)sence image:(UIImage *)image {
    DLWeChatShareMsgModel *msgModel = [[DLWeChatShareMsgModel alloc] init];
    msgModel.shareImage = image;
    SendMessageToWXReq *req = [self requestObjectWithMessageModel:msgModel scene:sence];
    [WXApi sendReq:req completion:^(BOOL success) {
        
    }];
}

#pragma mark - 分享处理
- (void)handleShareActionWithPlatformType:(DLWeChatPayOrAuthCustomPlatformType)platformType userInfo:(NSDictionary *)userInfo{
    if(platformType == DLWeChatPayOrAuthCustomPlatformTypeWechatSession){
        SendMessageToWXReq *req = [self requestObjectWithMessageModel:self.shareMsgModel scene:WXSceneSession];
        [WXApi sendReq:req completion:^(BOOL success) {
            
        }];
    }else if(platformType == DLWeChatPayOrAuthCustomPlatformTypeWechatTimeLine){
        SendMessageToWXReq *req = [self requestObjectWithMessageModel:self.shareMsgModel scene:WXSceneTimeline];
        [WXApi sendReq:req completion:^(BOOL success) {
            
        }];
    }else{
        if([self.delegate respondsToSelector:@selector(dl_shareCustomePlatform:withUserInfo:)]){
            [self.delegate dl_shareCustomePlatform:platformType withUserInfo:userInfo];
        }
    }
}

- (SendMessageToWXReq *)requestObjectWithMessageModel:(DLWeChatShareMsgModel *)shareMsgModel scene:(enum WXScene)scene{
    
    WXWebpageObject *ext = [WXWebpageObject object];
    ext.webpageUrl = shareMsgModel.mediaURL;
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = self.shareMsgModel.title;
    message.description = self.shareMsgModel.content;
    message.mediaObject = ext;
    message.messageExt = nil;
    message.messageAction = nil;
    message.mediaTagName = nil;
    if(shareMsgModel.thumbURL){
        NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:shareMsgModel.thumbURL]];
        UIImage *thumbImg = [UIImage imageWithData:imgData];
        //缩略图不能超过32KB
        [message setThumbImage:[self compressImageSize:thumbImg toByte:32*1024]];
    }
    if(shareMsgModel.shareThumbImage){
        //缩略图不能超过32KB
        [message setThumbImage:[self compressImageSize:shareMsgModel.shareThumbImage toByte:32*1024]];
    }
    if (shareMsgModel.shareImage) {
        WXImageObject *imgObjc = [WXImageObject new];
        //分享图片不能超过10M
        UIImage *compressionImg = [self compressImageSize:shareMsgModel.shareImage toByte:10*1024*1024];
        NSData *data = UIImagePNGRepresentation(compressionImg);
        imgObjc.imageData = data;
        message.mediaObject = imgObjc;
    }
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.message = message;
    req.bText = NO;
    req.scene = scene;
    return req;
}

#pragma mark - 微信分享回调
- (void)handleOpenWechatResp:(BaseResp *)resp{
    SendMessageToWXResp *response = (SendMessageToWXResp*)resp;
    [self handleResultWithSuccess:(response.errCode == 0) errorCode:response.errCode platformType:self.currentType withErrorStr:response.errStr];
}

#pragma mark - 友盟分享结果处理
- (void)handleMessageBack:(id)data error:(NSError *)error{
    self.shareMsgModel = nil;
    if (error) {
        NSLog(@"友盟分享失败：%@",error);
        if(self.dl_sharedMessageCallBack){
            self.dl_sharedMessageCallBack(NO, data, error);
        }
        if([self.delegate respondsToSelector:@selector(dl_sharedMessageCallBack:responseData:error:)]){
            [self.delegate dl_sharedMessageCallBack:NO responseData:data error:error];
        }
    }else{
        if ([data isKindOfClass:[UMSocialShareResponse class]]) {
            UMSocialShareResponse *resp = data;
            NSLog(@"友盟分享返回数据：%@，第三方应用返回原始数据：%@",resp.message,resp.originalResponse);
            if(self.dl_sharedMessageCallBack){
                self.dl_sharedMessageCallBack(YES, resp, error);
            }
            if([self.delegate respondsToSelector:@selector(dl_sharedMessageCallBack:responseData:error:)]){
                [self.delegate dl_sharedMessageCallBack:YES responseData:resp error:error];
            }
        }else{
            NSLog(@"友盟分享返回数据：%@",data);
            if(self.dl_sharedMessageCallBack){
                self.dl_sharedMessageCallBack(YES, data, error);
            }
            if([self.delegate respondsToSelector:@selector(dl_sharedMessageCallBack:responseData:error:)]){
                [self.delegate dl_sharedMessageCallBack:YES responseData:data error:error];
            }
        }
    }
}

#pragma mark - 处理结果回调
- (void)handleResultWithSuccess:(BOOL)success errorCode:(int)errorCode platformType:(DLWeChatPayOrAuthCustomPlatformType)type withErrorStr:(NSString *)errorStr{
    UMSocialShareResponse *response = [UMSocialShareResponse new];
    response.platformType = type;
    response.message = errorStr;
    if(self.dl_sharedMessageCallBack){
        self.dl_sharedMessageCallBack(success, response, nil);
    }
    if([self.delegate respondsToSelector:@selector(dl_sharedMessageCallBack:responseData:error:)]){
        [self.delegate dl_sharedMessageCallBack:success responseData:response error:nil];
    }
    WXShareCallBackStatusType statusType;
    if (errorCode == WXSuccess) {
        statusType = WXShareCallBackStatusTypeSuccess;
    }else if (errorCode == WXErrCodeUserCancel){
        statusType = WXShareCallBackStatusTypeCancel;
    }else{
        statusType = WXShareCallBackStatusTypeFail;
    }
    if ([self.delegate respondsToSelector:@selector(dl_sharedMessageCallBackStatusType:responseData:error:)]) {
        [self.delegate dl_sharedMessageCallBackStatusType:statusType responseData:response error:nil];
    }
    if (self.dl_shareMessageWithStatusCallBack) {
        self.dl_shareMessageWithStatusCallBack(statusType, response, nil);
    }
}

#pragma mark - Methods
- (void)dl_shareAddCustomePlatform:(DLWeChatPayOrAuthCustomPlatformType)platformType iconImage:(UIImage *)iconImage platformName:(NSString *)platformName{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wenum-conversion"
    
    [UMSocialUIManager addCustomPlatformWithoutFilted:platformType withPlatformIcon:iconImage withPlatformName:platformName];
    
#pragma clang diagnostic pop
}

#pragma mark - UMSocialShareMenuViewDelegate
- (void)UMSocialShareMenuViewDidAppear{
    [self handMenuViewDisPlay:YES];
}

- (void)UMSocialShareMenuViewDidDisappear{
    [self handMenuViewDisPlay:NO];
}

- (void)handMenuViewDisPlay:(BOOL)isShow{
    if(self.dl_sharedMenuViewDisPlayBlock){
        self.dl_sharedMenuViewDisPlayBlock(isShow);
    }
    if([self.delegate respondsToSelector:@selector(dl_sharedMenuViewDisPlay:)]){
        [self.delegate dl_sharedMenuViewDisPlay:isShow];
    }
}

#pragma mark - 压缩图片
//压缩图片到指定大小内
- (UIImage *)compressImageSize:(UIImage *)image toByte:(NSUInteger)maxLength
{
    //首先判断原图大小是否在要求内，如果满足要求则不进行压缩，over
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    //原图大小超过范围，先进行“压处理”，这里 压缩比 采用二分法进行处理，6次二分后的最小压缩比是0.015625，已经够小了
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    //判断“压处理”的结果是否符合要求，符合要求就over
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    
    //缩处理，直接用大小的比例作为缩处理的比例进行处理，因为有取整处理，所以一般是需要两次处理
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        //获取处理后的尺寸
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio)));
        //通过图片上下文进行处理图片
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        //获取处理后图片的大小
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    
    return resultImage;
}
@end
